var cartList=[];

//提交订单
function submitOrder(el){
	var oid = $(el).attr('oid');
	var deliveryTime = $('#deliveryTime').val();
	//展开前
	var contacted = $('#contacted').text();
	var teled = $('#teled').text();
	var addressed = $('#addressed').text();
	//展开后
	var username = $('#username').val();
	var mobile = $('#mobile').val();
	var address = $('#address').val();
	
	if($('#contacted').length==0 || $('#contacted').is(':hidden')){
			//validate
			if(isNull(username)||isNull(mobile)||isNull(address)){
				alert('亲，信息不完整哦');
				return false;
			}
		    if(mobile.length!=11)
			{
				alert('请输入有效的手机号码！');
				return false;
			}
			
			var myreg = /^1[3|4|5|7|8][0-9]\d{4,8}$/;
			if(!myreg.test(mobile))
			{
				alert('请输入有效的手机号码！');
				return false;
			}
			contacted = username;
			teled = mobile;
			addressed = address;
	}
	
	if(isNull(oid) ||isNull(deliveryTime) ||isNull(contacted) ||isNull(teled) ||isNull(addressed)){
		alert('信息填写不完整');
		return false;
	}
	$('#submitBtn').attr("disabled","true");
	
	$.ajax({
 	  type: "post", 
 	  url : "/order/confirm", 
 	  dataType: 'json',
 	  data: {'oid':oid,'deliveryTime':deliveryTime,'contact':contacted,'tel':teled,'address':addressed},
	  complete: function () {
        $('#submitBtn').attr("disabled","false");
	  },
 	  success: function(info){
		  var msg = info.msg;
		  if(!isNull(msg)&&msg =='success'){
			clearCookie('cart');
			location.href='/order';
		  }
		  if(!isNull(msg)&&msg =='dataNeed'){
			  alert('信息填写不完整');
			  return false;
		  }
		  if(!isNull(msg) &&msg=='fail'){
			  alert('提交失败');
			  return false;
		  }
 	  },
	  error:function(){
		  $('#submitBtn').attr("disabled","false");
		  alert('提交失败');
		  return false;
	  }
 });
}
//去结算
 function toJieSuan(){
	 var list = [];
	 $('.gouxuan').each(function(index,el){
		 if($(el).attr('tag')=='1'){
			 var productId = $(el).attr('pid');
			 var eid = $(el).attr('eid');
			 var cid = $(el).attr('cid');
			 var num = $(el).next().next().find('input').val();
			 var oneRow = [];
			 oneRow.push(productId);
			 oneRow.push(num);
			 oneRow.push(cid);
			 oneRow.push(eid);
			 var one = oneRow.join(';');
			 list.push(one);
		}
	 });
	 var Pricrtotal = $('#total').text();
	 
	 if(Pricrtotal == 0){
		 alert('购物车数量为0！请重新选择数量！');
		 return false;
	 }
	 if(typeof(list)!='array' && list.length==0){
		 alert('请选择需要结算的商品');
		 return false;
	 }
	 $.ajax({
	 	  type: "post", 
	 	  url : "/product/cart", 
	 	  dataType: 'text',
	 	  data: 'list='+list,
	 	  success: function(info){
				if(isNull(info)){return;}
				var msg = info.split('&')[0];
				var orderId = info.split('&')[1];
	 			if(msg=='success'&&!isNull(orderId)){
					location.href="/order/confirm?id="+orderId;
					return false;
				}
				if(msg=='fail'){
					alert('结算失败!');
					return false;
				}
				if(msg=='login'){
					location.href="/login";
				}
	 	  },
		  error:function(){
			  alert('结算失败');
			  return false;
		  }
	 });
 }

function isNull(arg1)
{
  return !arg1 && arg1!==0 && typeof arg1!=="boolean"?true:false;
}

//读取cookies
function getCookie(name) 
{ 
  var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
  if(arr=document.cookie.match(reg))
	return unescape(arr[2]); 
  else 
    return null; 
}

//写cookies 
function setCookie(name,value) 
{ 
  var Days = 1; 
  var exp = new Date(); 
  exp.setTime(exp.getTime() + Days*24*60*60*1000); 
  document.cookie = name + "="+ escape (value) + ";path=/;expires=" + exp.toGMTString(); 
} 
//清除cookie  
function clearCookie(name) {  
    setCookie(name, "", -1);  
}
function clickCart(el){
	$(el).find('span').show();
	$(el).attr('tag','1');
	var productId = $(el).attr('productId');
	var channelId = $(el).attr('channelId');
	var enterpriseId = $(el).attr('enterpriseId');
	var num = $(el).children().find('input[name=newCart]').val();
	if(num=='0'){
		num='1';
	}else{
		num = num;
	}
	//alert(num);
	if(!isExist(cartList,productId)){
		$('#cartNum').html(parseInt($('#cartNum').text())+1);
		var one = [];
		one.push(productId);
		one.push(channelId);
		one.push(enterpriseId);
		one.push(num);
		var oneRow = [];
		oneRow = one.join(';');
		cartList.push(oneRow);
		addProductToCookie(cartList);
	}
}
function loadCookie(){
	var cart = getCookie('cart');
	if(isNull(cart)){
		return false;
	}
	var row = cart.split(',');
	$('#cartNum').html(row.length);
	for (var i =0;i<row.length;i++){
		var rowStr = row[i];
		cartList.push(rowStr);
		var rowArr = rowStr.split(';');
		var productId  = rowArr[0];
		$('.cart').each(function(index,el){
			if($(el).attr('productId')== productId){
				$(el).find('span').show();
			}
		});
	}
}
function isExist(cartList,productId){
	var cartListLength = cartList.length;
	if(cartListLength>=1){
		for(var i=0;i<cartListLength;i++){
			var row = cartList[i];
			var rowArr = row.split(';');
			var listProductId = rowArr[0];
			if(listProductId == productId){
				return true;
				break;
			}
		}
	}else{
		return false;
	}
}
function addProductToCookie(cartList){
	setCookie('cart',cartList);
}
function addCart(el){
	var inputVal = $(el).prev().find('input').val();
	var newVal = parseInt(inputVal)+1;
	$(el).prev().find('input').val(newVal);

	//num 2016.3.30
	var productId =$(el).attr('pid');
	//alert(productId);
	var oldCart = getCookie('cart');
	var cartArr = oldCart.split(',');
	for (var i = 0; i < cartArr.length; i++) {
		var arrString = cartArr[i];
		if (arrString.indexOf(productId) != -1) {
			var productInfo = arrString.split(';');
			var productNum = parseInt(newVal);
			productInfo[3] = productNum;
			cartArr[i] = productInfo.join(';');
		}
	}
	setCookie('cart',cartArr.join(','));
	total();
}
function addCartindex(el){
	var inputVal = $(el).prev().find('input').val();
	var newVal = parseInt(inputVal)+1;
	$(el).prev().find('input').val(newVal);
	//num 2016.3.30
	var productId =$(el).attr('productId');
	if(isExist(cartList,productId)){
		for (var i = 0; i < cartList.length; i++) {
			var arrString = cartList[i];
			if (arrString.indexOf(productId) != -1) {
				var productInfo = arrString.split(';');
				var productNum = parseInt(newVal);
				productInfo[3] = productNum;
				cartList[i] = productInfo.join(';');
			}
		}
	}else{
		var productId = $(el).attr('productId');
		var channelId = $(el).attr('channelId');
		var enterpriseId = $(el).attr('enterpriseId');
		var num = 1;
		var oneItem = [];
		oneItem.push(productId);
		oneItem.push(channelId);
		oneItem.push(enterpriseId);
		oneItem.push(num);
		cartList.push(oneItem.join(';'));
	}
	setCookie('cart',cartList);
	countCart();//统计购物车

	total();
}
function minus(el){
	var inputVal = $(el).next().find('input').val();
	var productId =$(el).attr('pid');
	if(inputVal<=0){
		return false;
	}
	var newVal = parseInt(inputVal)-1;
	$(el).next().find('input').val(newVal);
	//prouduct
	var productId =$(el).attr('pid');
	//2015 5.17 当数量为0 删除购物车产品
	if(newVal==0){
		if(confirm('你确定要删除产品?')){
			delCart(productId);
			countCart();
			location.reload();
		}else{
			$(el).next().find('input').val('1');
			return false;
		}
	}
	//alert(productId);
	var oldCart = getCookie('cart');
	var cartArr = oldCart.split(',');
	for (var i = 0; i < cartArr.length; i++) {
		var arrString = cartArr[i];
		if (arrString.indexOf(productId) != -1) {
			var productInfo = arrString.split(';');
			var productNum = parseInt(newVal);
			productInfo[3] = productNum;
			cartArr[i] = productInfo.join(';');
		}
	}
	setCookie('cart',cartArr.join(','));
	countCart();
	total();
}
//2016.3.30,
function minusindex(el){
	var inputVal = $(el).next().find('input').val();
	var productId =$(el).attr('productId');
	if(inputVal==1){
		delCart(productId);
	}
	if(inputVal==0){
		alert('数量要大于0');
		return false;
	}
	var newVal = parseInt(inputVal)-1;
	$(el).next().find('input').val(newVal);
	//prouduct

	//alert(productId);
	var oldCart = getCookie('cart');
	var cartArr = oldCart.split(',');
	for (var i = 0; i < cartArr.length; i++) {
		var arrString = cartArr[i];
		if (arrString.indexOf(productId) != -1) {
			var productInfo = arrString.split(';');
			var productNum = parseInt(newVal);
			productInfo[3] = productNum;
			cartArr[i] = productInfo.join(';');
		}
	}
	setCookie('cart',cartArr.join(','));
	countCart();
	total();
}
function checkInt(el){
	//alert(1111);
	var inputVal = $(el).val();
	var r = /^[-+]?\d*$/;
	if(!r.test(inputVal)){
		alert('请输入整数');
		location.href = location.href;
		// $(el).val(0);
		return false;
	}
	if(isNaN(inputVal) || inputVal<0){
		alert('输入有误');
		// $(el).val(0);
		location.href = location.href;
		return false;
	}
	
	if(inputVal == 0){
		$(el).val(0);
		return;
	}
	var productId =$(el).attr('productId');
	if(isExist(cartList,productId)){
		for (var i = 0; i < cartList.length; i++) {
			var arrString = cartList[i];
			if (arrString.indexOf(productId) != -1) {
				var productInfo = arrString.split(';');
				var productNum = parseInt(inputVal);
				productInfo[3] = productNum;
				cartList[i] = productInfo.join(';');
			}
		}
	}else{
		//cartlist push
		//$(el).attr('productId') + ';' + $(el).attr('channelId') + ';' + $(el).attr('enterpriseId') + ';1');
		var productId = $(el).attr('productId');
		var channelId = $(el).attr('channelId');
		var enterpriseId = $(el).attr('enterpriseId');
		var num = inputVal;
		var oneItem = [];
		oneItem.push(productId);
		oneItem.push(channelId);
		oneItem.push(enterpriseId);
		oneItem.push(num);
		cartList.push(oneItem.join(';'));
	}
	setCookie('cart',cartList);
	countCart();
	total();
}
//购物车输入框
function checkIntcart(el){

	var inputVal = $(el).val();
	var productId =$(el).attr('productId');
	if(isNaN(inputVal) || inputVal<0){
		alert('输入有误');
		location.href = location.href;
		return false;
	}
	if(inputVal == 0){
		if(confirm('你确定要删除产品?')){
			delCart(productId);
			countCart();
			location.reload();
			//var removecartRight = $(el).parent().parent().parent('.page-product-right');
			//var removegun = $(el).parent().parent().parent('.page-product-right').siblings('.gouxuan');
			//var removeimg = $(el).parent().parent().parent('.page-product-right').siblings('.page-product1-img');
			//removecartRight.remove();
			//removegun.remove();
			//removegun.remove();

		}else{
			$(el).val('1');
		}
		total();
		countCart();
		return;
		// return false;
	}
	// alert(inputVal);return;
	var  cartList = getCookie('cart').split(',');
	if(isExist(cartList,productId)){
		for (var i = 0; i < cartList.length; i++) {
			var arrString = cartList[i];
			if (arrString.indexOf(productId) != -1) {
				var productInfo = arrString.split(';');
				var productNum = parseInt(inputVal);
				productInfo[3] = productNum;
				cartList[i] = productInfo.join(';');
			}
		}
	}
	setCookie('cart',cartList);
	total();
	countCart();
}

//删除购物车
function delCart(productId){
	var oldCart = getCookie('cart');
	var cartArr = oldCart.split(',');
	var newCart = [];
	for (var i = 0; i < cartArr.length; i++) {
		var arrString = cartArr[i];
		var productInfo = arrString.split(';');
		if(productInfo[0]!=productId){
			newCart.push(arrString);
		}
		//alert(productInfo);
		//if((productInfo[3]!=1)&&(productId!=productInfo[0])){
		//	newCart.push(arrString);
		//}
	}
	setCookie('cart',newCart.join(','));
	countCart();
}
function total(){
	var total = 0;
	$('.gouxuan').each(function(index,el){
		if($(el).attr('tag')==1){
			var num = $(el).next().next().find('input').val();
			var cprice = $(el).attr('cprice');
			total = total + parseFloat(cprice)*parseInt(num);
		}
	});
	
	$('#total').html(parseFloat(total).toFixed(2));
}

function resetCookie(){
	clearCookie('cart');
	//location.href="/product";
	history.back();
	}
	function selectOne(el){
		var tag = $(el).attr('tag');
		var len = document.getElementsByClassName('gouxuan');
		if(tag==0){
			$(el).attr('tag','1');
			$(el).find('img').attr('src','../public/img/shopcart_chk_selected.png');
		}
		if(tag==1){
			$(el).attr('tag','0');
			$(el).find('img').attr('src','../public/img/shopcart_chk_normal.png');
		}
		if ($('div[tag=1]').length-1>=len.length) {
            $('#selectAll').find('img').attr('src','../public/img/shopcart_chk_selected.png');
        }else if ($('div[tag=0]').length>=1) {
        	$('#selectAll').find('img').attr('src','../public/img/shopcart_chk_normal.png');
        }
		total();
	}
	function selectAll(el){
		var tag = $(el).attr('tag');
		if(tag==0){
			$(el).attr('tag','1');
			$(el).find('img').attr('src','../public/img/shopcart_chk_selected.png');
			$('.gouxuan').each(function(index,ele){
				if($(ele).attr('tag')!='1'){
					$(ele).attr('tag','1');
					$(ele).find('img').attr('src','../public/img/shopcart_chk_selected.png');
				}
			});
		}
		if(tag==1){
			$(el).attr('tag','0');
			$(el).find('img').attr('src','../public/img/shopcart_chk_normal.png');
			$('.gouxuan').each(function(index,ele){
				if($(ele).attr('tag')!='0'){
					$(ele).attr('tag','0');
					$(ele).find('img').attr('src','../public/img/shopcart_chk_normal.png');
				}
			});
		}
		total();
	}
/**
 * 检查产品是否下架
 */
	function checkoutproduct(){
		var cartList = getCookie('cart');
	    var tmpobj = {};
	    if(cartList.length>0){
			var cartArr = cartList.split(',');
			for(var i=0;i<cartArr.length;i++){
				var product = cartArr[i].split(';');
				tmpobj[product[0]] = product[1];
			}
			//ajax 检查产品是否下线
			var data = JSON.stringify(tmpobj);
			$.ajax({
				'url':'product/checkproduct',
				'type':'POST',
				'data':{
					'data':data
				},
				success:function(res){
					try{
						var items = JSON.parse(res);
						if(items.result=='OK'){
							var data = items.data;
							for(var i=0;i<data.length;i++){
								var productId = data[i].productId;
								var productData = data[i].product;
								if(productData.length==0){
									delCart(productId);
									countCart();
								}
							}
						}
					}catch(e){
						console.log(e.name+':'+e.message);
					}
				}
			});
		}
	}
	//购物车统计
    function countCart(){
		var cartnum = getCookie('cart');
		var count = cartnum.split(',');
		var cartcount = count.length;
		//alert(cartcount);
		$('#cartNum').html(cartcount);
	}








